package com.wuhao.springboot.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.wuhao.springboot.entity.User;
import com.wuhao.springboot.entity.vo.TokenInfoVO;
import com.wuhao.springboot.exception.ServiceException;
import com.wuhao.springboot.service.IUserService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.*;

@Component
public class TokenUtils {

    private static IUserService staticUserService;

    @Resource
    private IUserService userService;

    @PostConstruct
    public void setUserService() {
        staticUserService = userService;
    }

    private static final String SECRET = "!Q@W#E$R^Y&U";
    //token签发者
    private static final String ISSUSRE = "HZSTYGZPT";
    //token过期时间
    public static final Long EXPIRE_DATE = 1000 * 60 * 60 *24L;

    /**
     * 生成token
     *
     * @return
     */
    public static String getToken(TokenInfoVO tokenInfoVO) {
        //当前时间
        Date now = new Date();
        //创建过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);  //7天过期
        //1. header
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        return JWT.create()
                .withIssuer(ISSUSRE)
                .withIssuedAt(now)
                .withExpiresAt(instance.getTime())
                .withClaim("userId", tokenInfoVO.getUserId())
                .sign(algorithm);
    }

    /**
     * 获取当前登录的用户信息
     *
     * @return user对象
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            String token = request.getHeader("token");
//            String decodeToken = URLDecoder.decode(token, "UTF-8");
//            Map<String, Object> map = JsonUtils.json2Map(decodeToken);
            if (StrUtil.isNotBlank(token)) {
                TokenInfoVO vo = TokenUtils.decodeJwt(token);
                return staticUserService.getById(vo.getUserId());
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    /**
     * @Author pq
     * @Description 解析token
     * @Date `17:31` 2023/1/31
     * @Param [token]
     * @return com.wuhao.springboot.entity.vo.TokenInfoVO
     **/
    public static TokenInfoVO decodeJwt(String token){
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        TokenInfoVO tokenInfoVO=new TokenInfoVO();
        tokenInfoVO.setUserId(Optional.ofNullable(jwt.getClaim("userId").asInt()).orElseThrow(()->new ServiceException(HttpStatus.OK.toString(),"token中id不存在，请登录！")));
        return tokenInfoVO;
    }
}